<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
  >
    <el-table :data="formData" class="-mt-10px">
      <el-table-column label="序号" type="index" width="100"/>
      <el-table-column label="名字" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.userId`" :rules="formRules.userId" class="mb-0px!">
            <!--            <el-input v-model="row.name" placeholder="请输入名字" />-->
            <el-select v-model="row.userId" @change="setDeptName(row,row.userId)" clearable
                       placeholder="请选择小组人员">
              <el-option
                v-for="item in userList"
                :key="item.id"
                :label="item.nickname"
                :value="item.id"
                :disabled="item.disabled"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="部门" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.deptName`" :rules="formRules.score" class="mb-0px!">
            <el-input v-model="row.deptName" placeholder="" disabled/>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="60">
        <template #default="{ $index }">
          <el-button @click="handleDelete($index)" link>—</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-form>
  <el-row justify="center" class="mt-3">
    <el-button @click="handleAdd" round>+ 添加组员</el-button>
  </el-row>
</template>
<script setup lang="ts">
import {Demo03StudentApi} from '@/api/infra/demo/demo03/normal'
import * as UserApi from "@/api/system/user";
import {BizSalesTeamApi} from "@/api/biz/salesteam";
import {a} from "vite/dist/node/types.d-jgA8ss1A";

const props = defineProps<{
  teamId: number, // 学生编号（主表的关联字段）
  teamMsg: any[] // 学生编号（主表的关联字段）
}>()
const formLoading = ref(false) // 表单的加载中
const formData = ref<any[]>([])
const formRules = reactive({
  // studentId: [{ required: true, message: '学生编号不能为空', trigger: 'blur' }],
  userId: [{required: true, message: '名字不能为空', trigger: 'blur'}],
  // score: [{ required: true, message: '分数不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
const userList = ref<UserApi.UserVO[]>([]) // 用户列表

/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
  () => props.studentId,
  async (val) => {
    try {
      formLoading.value = true
      userList.value = await UserApi.getSimpleUserList()
      // 1. 重置表单
      formData.value = []
      // console.info(props.teamMsg)
      userList.value.forEach(i => {
        props.teamMsg.forEach(j => {
          if (i.id === j.id) {
            i.userId = j.id;
            i.disabled = true
            formData.value.push(i)
          } else {
            i.disabled = false
          }
        })
      })
      // 2. val 非空，则加载数据
      if (!val) {
        return
      }

    } finally {
      formLoading.value = false
    }
  },
  {immediate: true}
)

/** 新增按钮操作 */
const handleAdd = () => {
  const row = {
    id: undefined,
    teamId: undefined,
    userId: undefined,
    // score: undefined,
  }
  row.teamId = props.teamId as any
  formData.value.push(row)
}

/** 删除按钮操作 */
const handleDelete = (index) => {
  formData.value.splice(index, 1)
}

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}

/** 表单值 */
const getData = () => {
  return formData.value
}
const message = useMessage() // 消息弹窗
const setDeptName = async (row, userId) => {
  // 判断是否存在其他组
  const user = await BizSalesTeamApi.getBizSalesTeamUser(userId)
  console.info(user.length)
  if (user.length > 0) {
    message.error("该组员已经存在其他分组，添加后将覆盖原有分组")
  }
  row.deptName = userList.value.find(item => item.id === userId).deptName
  // userList.value.find(item => item.id === userId).disabled = true
}

defineExpose({validate, getData})
</script>
